package com.micai.boss.sso.resource.filter;

import com.micai.boss.sso.resource.auth.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述：JwtFilter enforces SSO. If JWT Token's not existed (unauthenticated), redirects to Authentication Service. If JWT Token's existed (authenticated), extracts user identity and forwards the request.
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/5/21 11:29
 */
@Component
public class JwtFilter extends OncePerRequestFilter {

    private static final String jwtTokenCookieName = "JWT-TOKEN";
    // 签名key
    private static final String signingKey = "signingKey";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        try {
            String username = JwtUtil.getSubject(request, jwtTokenCookieName, signingKey);
            if (username == null) {
                String authService = this.getFilterConfig().getInitParameter("services.auth");
                response.sendRedirect(authService + "?redirect=" + request.getRequestURL());
            } else {
                request.setAttribute("username", username);
                filterChain.doFilter(request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
